package cm.unit3.theme3;

public class Power {

	public double Power(double base, int exponent) {
		double result = 1;
		
		if (exponent<0) {
			exponent *=-1;
			base = 1.0/base;
		}
		for (int i = 0; i < exponent; i++) {
			result *= base;
		}
		return result;
	}
	/**
	 * 0的0次方没有意义
	 * 1的n次方定义本身
	 * 
	 */
	public double Power01(double base, int exponent) {
		 if (base==1.0 || exponent==0) {
			 return 1.0;
		 }
		 if (exponent==1){
		     return base;
         }

		 // 先处理exponent是负数
	     if (exponent<0) {
			 return Power(1/base,-1*exponent);
		 }
	     if (exponent%2!=0) {
			 return Power(base, exponent-1)*Power(base, 1);
		 }else {
			 return (double)Power(((int)base)<<1, exponent>>1);
//			 return Power(base, exponent>>1)*Power(base, exponent>>1);
		 }
	}

	public static final double MIN_VALUE = Double.MIN_VALUE;    // 1.0E-12
	public static boolean equalsOfDouble(double a,double b){
	    if ( Math.abs(a-b)<MIN_VALUE ){
	        return true;
        }else{
	        return false;
        }
    }

    public double Power02(double base, int exponent) {
	    // (0,-1) -> 防止对0求导
        if( equalsOfDouble(base,0.0) && (exponent<0) ){
            // 可以使用异常标志
            return 0.0;
        }

        if ( equalsOfDouble(base,1.0) || exponent==0) {
            return 1.0;
        }

        double result = PowerWithUnsignedExponent(base,Math.abs(exponent));
        // 先处理exponent是负数
        if (exponent<0) {
            return 1/result;
        }
        return result;
    }
    
    public static double PowerWithUnsignedExponent(double base, int exponent){
	    if (exponent==0){
	        return 1;
        }
	    if (exponent==1){
	        return base;
        }
        double result = PowerWithUnsignedExponent(base, exponent >> 1);
	    result *= result;       // 翻倍
        if ((exponent & 0x1) == 1){// 判断奇/偶数
            result *= base;
        }
        return result;
    }


	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Power power = new Power();
		for (int i = 1; i <= 10; i++) {
            System.out.println("========== " + i + " ===========");
            System.out.println(power.Power(2, i));
			System.out.println(power.Power(2, -1*i));
            System.out.println(power.Power(-1*2, i));
            System.out.println(power.Power(-1*2, -1*i));
            System.out.println("___________________");
            System.out.println(power.Power02(2, i));
			System.out.println(power.Power02(2, -1*i));
            System.out.println(power.Power02(-1*2, i));
            System.out.println(power.Power02(-1*2, -1*i));
//            System.out.println(power.Power01(2, i));
//			  System.out.println(power.Power01(2, -1*i));
//            System.out.println(power.Power01(-1*2, i));
//            System.out.println(power.Power01(-1*2, -1*i));
		}
	}

}
